package thread;

/**
 * @author liweimin
 * @date 2021/1/21 16:06
 * @description
 * @since
 */

import org.junit.Test;

public class ThreadTest {

    @Test
    public void testYield() {
        HelloThread thread = new HelloThread();
        thread.start();
        for (int i = 0; i < 100; i++) {
            if (i % 2 == 0) {
                System.out.println(i + "********");
            }

        }
    }

    @Test
    public void testJoin() {
        MyThread thread = new MyThread();
        thread.start();

    }

    @Test
    public void testPriority() {
        HelloThread thread = new HelloThread();
        thread.setPriority(Thread.MAX_PRIORITY);
        thread.setName("最高优先级");
        HelloThread thread1 = new HelloThread();
        thread1.setPriority(Thread.MIN_PRIORITY);
        thread1.setName("最低优先级");
        thread1.start();
        thread.start();
    }

    public static class MyThread extends Thread {
        @Override
        public void run() {
            for (int i = 0; i < 10000; i++) {
                if (i % 2 == 0) {
                    System.out.println(i);
                }
                if (i % 20 == 0) {
                    try {
                        //自己等自己----->死锁
//                        join(1000);
                        join();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public class HelloThread extends Thread {
        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                if (i % 2 == 0) {
                    System.out.println(i + " " + Thread.currentThread().getName());
                }
                if (i % 20 == 0) {
                    //当i==20时，让出CPU执行权，CPU通过调度算法选择下一个执行的线程
                    yield();
                }
            }
        }
    }

    public static void main(String[] args) {
        new MyThread().start();
    }
}
